from flask_uploads import UploadSet, configure_uploads, patch_request_class, extension, UploadNotAllowed, send_from_directory
from . import upload_blueprint
from flask import request, jsonify, current_app
import uuid
import time
import os
from PIL import Image

photos = UploadSet('PHOTO')


def get_current_date():
    time_tuple = time.localtime(time.time())
    str1 = str(time_tuple[0])
    str2 = str(time_tuple[1])
    str3 = str(time_tuple[2])
    if time_tuple[1] < 10:
        str2 = '0'+str(time_tuple[1])
    if time_tuple[2] < 10:
        str3 = '0'+str(time_tuple[2])
    return str1 + str2 + str3


def get_ext(file):
    return extension(file.filename)


@upload_blueprint.route('/upload/<upload_type>', methods=["POST", "GET"])
def upload(upload_type):
    if upload_type == 'images':
        up_set = photos
        up_prefix = '/images/'
    print(request.files)
    if request.method == 'POST' and 'file' in request.files:
        try:
            print(request.files['file'])
            filename = up_set.save(request.files['file'],
                                   get_current_date(),
                                   str(uuid.uuid1())+'.'+get_ext(request.files['file']))
        except UploadNotAllowed:
            return jsonify({
                'state': 400,
                'msg': '类型不支持'
            })
        filein = os.path.join(up_set.config.destination, filename)
        img = Image.open(filein)
        return jsonify({
                'state': 200,
                'url': up_prefix+filename,
                'size': {
                    'height': img.size[1],
                    'width': img.size[0]
                }
            })


@upload_blueprint.route('/images/<folder>/<filename>')
def show_images(folder, filename):
    return send_from_directory(photos.config.destination+folder, filename)


@upload_blueprint.route('/qrcode/<filename>')
def show_qrcode(filename):
    return send_from_directory(current_app.config.get('LOGIN_QR_PATH'), filename)


def init_upload(app):
    configure_uploads(app, photos)
    app.register_blueprint(upload_blueprint)
    patch_request_class(app, None)
